package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*@Override
    public Result queryById(Long id) {
        // 缓存穿透问题解决
        // 从 redis 查询 商铺缓存
        // CACHE_SHOP_KEY = "cache:shop:"
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)){
            // 存在 直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        if (shopJson != null){
            return Result.fail("商铺不存在");
        }
        // 不存在 从数据库查询
        Shop shop = getById(id);
        // 从数据库查询不存在 返回错误信息
        if (shop == null) {
            return Result.fail("商铺不存在");
        }
        // 存在 写入 redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop)
                ,CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 不存在
        if (shop == null){
            // 将空写入 REDIS
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",
                    CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("商铺不存在");
        }
        // 返回
        return Result.ok(shop);
    }*/

    // 用互斥锁解决缓存击穿
    @Override
    public Result queryById(Long id) {
        // 互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);
        // 逻辑过期解决缓存击穿
        Shop shop = queryWithLogicalExpire(id);

        if (shop != null){
            return Result.fail("商铺不存在");
        }
        return Result.ok(shop);
    };


    /**
     * 自定义线程池
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR
            = Executors.newFixedThreadPool(10);












    /**
     * 逻辑过期解决缓存击穿
     * @return
     */
    public Shop queryWithLogicalExpire(Long id) {
        String key = LOCK_SHOP_KEY + id;
        // 从redis查询缓存数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在，反序列化并返回
            RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
            JSONObject data = (JSONObject) redisData.getData();
            Shop shop = JSONUtil.toBean(data, Shop.class);
            LocalDateTime expireTime = redisData.getExpireTime();

            // 判断是否过期
            if (expireTime != null && expireTime.isAfter(LocalDateTime.now())) {
                // 未过期，直接返回店铺信息
                return shop;
            }

            // 已过期，需要重建缓存
            // 6.1 获取互斥锁
            String lockKey = LOCK_SHOP_KEY + id;
            boolean isLock = tryLock(lockKey);

            // 6.2 判断是否获取锁成功
            if (isLock) {
                // 6.3 成功，开启独立线程实现缓存重建
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    try {
                        // 重建缓存
                        this.saveShop2Redis(id, 30L);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        // 释放锁
                        unlock(lockKey);
                    }
                });
            }
        }
        return null; // 如果缓存不存在或已过期，返回null
    }
















    public Shop queryWithMutex(Long id) {
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)){
            // 存在 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if (shopJson != null){
            return null;
        }
        // 4实现缓存重建

        // 4.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY  + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            // 4.2 判断是否获取成功
            if (!isLock){
                // 获取锁失败 休眠并重试
                try {
                    Thread.sleep(50);
                    queryWithMutex(id);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            }
            // 4.3 获取锁失败 休眠并重试

            // 成功
            // 不存在 从数据库查询
            shop = getById(id);
            // 模拟重建延迟
            Thread.sleep(200);
            // 从数据库查询不存在 返回错误信息
            if (shop == null) {
                return null;
            }
            // 存在 写入 redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop)
                    ,CACHE_SHOP_TTL, TimeUnit.MINUTES);

            // 不存在
            if (shop == null){
                // 将空写入 REDIS
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",
                        CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            unlock(lockKey);
        }

        // 释放锁

        // 返回
        return shop;
    }




    // 用 redis 实现分布式锁
    private boolean tryLock(String key){
        // 锁的 key
        Boolean flag =
                stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);

        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }




    private void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        // 查询店铺数量
        Shop shop = getById(id);
        Thread.sleep(200);
        // 封装过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 封装逻辑过期时间
        // 写入 Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));

    }



    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("商铺id不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
